package com.lzy.wzy.controller;


import com.google.gson.Gson;
import com.lzy.wzy.constant.MyConstant;
import com.lzy.wzy.mapper.WorkMapper;
import com.lzy.wzy.model.LevelOneTemplateBean;
import com.lzy.wzy.result.Result;
import com.lzy.wzy.service.IndexService;
import com.lzy.wzy.token.MyUsernamePasswordToken;
import com.lzy.wzy.utils.PatternUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/index")
@Slf4j
public class IndexController {

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private IndexService indexService;

    @Autowired
    private Gson gson;

    @RequestMapping(value = "/none/toLogin", method = RequestMethod.GET)
    public String index() {
        return "login";
    }

    @RequestMapping(value = "/none/main", method = RequestMethod.GET)
    public String main() {
        return "index";
    }

    @RequestMapping(value = "/none/test", method = RequestMethod.GET)
    public String ssss() {
        return "test";
    }

    //@PreAuthorize("@el.check('ROLE_CRAFT','ROLE_ADMIN')")
    @PreAuthorize("@el.check('ROLE_CRAFT','ROLE_ADMIN')")
    @RequestMapping(value = "/check/checkCraft", method = RequestMethod.GET)
    @ResponseBody
    public Result<T> checkCraft() {
        return Result.success();
    }

    @RequestMapping(value = "/page/craft", method = RequestMethod.GET)
    public String craft() {
        return "craft";
    }

    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/check/checkAdmin", method = RequestMethod.GET)
    @ResponseBody
    public Result<T> checkAdmin() {
        return Result.success();
    }

    @RequestMapping(value = "/page/admin", method = RequestMethod.GET)
    public String admin() {
        return "admin";
    }


    @PreAuthorize("hasAnyAuthority('ROLE_PLAN','ROLE_PRODUCE_DIRECTOR','ROLE_SUPERVISOR','ROLE_CRAFT','ROLE_QUALITY','QUALITY_INSPECTION','ROLE_ADMIN','ROLE_OTHER')")
    @RequestMapping(value = "/check/checkHours", method = RequestMethod.GET)
    @ResponseBody
    public Result<T> checkHours() {
        return Result.success();
    }

    @RequestMapping(value = "/page/hours", method = RequestMethod.GET)
    public String hours() {
        return "hours";
    }

    @PreAuthorize("hasAnyAuthority('ROLE_PLAN','ROLE_PRODUCE','ROLE_CRAFT','ROLE_QUALITY','QUALITY_INSPECTION','ROLE_ADMIN','ROLE_OTHER')")
    @RequestMapping(value = "/check/checkTemplatePage", method = RequestMethod.GET)
    @ResponseBody
    public Result<T> checkTemplatePage(@NotBlank @RequestParam("workOrderNumber") String workOrderNumber) {
        if (!PatternUtils.checkWorkOrderNumber(workOrderNumber)) {
            return Result.invalidFormat();
        }
        List<LevelOneTemplateBean> list = indexService.issueTemplate(workOrderNumber);
        if (list.isEmpty()) {
            return Result.failure("未绑定模板");
        }
        return Result.success();
    }

    @PreAuthorize("hasAnyAuthority('ROLE_PLAN','ROLE_PRODUCE','ROLE_QUALITY','QUALITY_INSPECTION','ROLE_CRAFT','ROLE_ADMIN','ROLE_OTHER')")
    @RequestMapping(value = "/page/template/{workOrderNumber}", method = RequestMethod.GET)
    public String template(@PathVariable("workOrderNumber") String workOrderNumber, Model model) {
        List<LevelOneTemplateBean> list = indexService.issueTemplate(workOrderNumber);
        String woStatus = workMapper.getWorkOrderStatus(workOrderNumber);

        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        List<String> authority = token.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

        boolean status = MyConstant.WorkOrderStatus.FINISHED.equals(woStatus)
                || MyConstant.WorkOrderStatus.CASECLOSE.equals(woStatus)
                || MyConstant.WorkOrderStatus.MAJOR_EXCEPTION.equals(woStatus)
                || !authority.contains(MyConstant.ApproveGroup.executorG);
        if (!list.isEmpty()) {
            model.addAttribute("workOrderNumber", workOrderNumber);
            model.addAttribute("template", list);
            model.addAttribute("status", !status);
            return "templateTwo";
        } else {
            model.addAttribute("message", "找不到模板");
            return "main";
        }
    }

    @PreAuthorize("hasAnyAuthority('ROLE_PRODUCE','ROLE_QUALITY','QUALITY_INSPECTION','ROLE_CRAFT','ROLE_ADMIN')")
    @RequestMapping(value = "/check/checkMrdPage", method = RequestMethod.GET)
    @ResponseBody
    public Result<T> checkMrdPage() {
        return Result.success();
    }


    @RequestMapping(value = "/page/mrdPage/{workOrderNumber}", method = RequestMethod.GET)
    public String toMrdPage(@PathVariable("workOrderNumber") String workOrderNumber, Model model) {
        List<LevelOneTemplateBean> list = indexService.issueTemplate(workOrderNumber);
        model.addAttribute("workOrderNumber", workOrderNumber);
        model.addAttribute("template", list);
        return "mrdPage";

    }

    @PreAuthorize("hasAnyAuthority('ROLE_PRODUCE','ROLE_PRODUCE_DIRECTOR','ROLE_SUPERVISOR')")
    @RequestMapping(value = "/loadTemplateList/{workOrderNumber}", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<LevelOneTemplateBean>> loadTemplateList(@PathVariable("workOrderNumber") String workOrderNumber) {
        if (!PatternUtils.checkWorkOrderNumber(workOrderNumber)) {
            return Result.invalidFormat();
        }
        return Result.success(indexService.issueTemplate(workOrderNumber));
    }

    //预检查
    @PreAuthorize("hasAnyAuthority('ROLE_CRAFT_DIRECTOR','ROLE_ADMIN')")
    @RequestMapping(value = "/checkTemplateManagement", method = RequestMethod.GET)
    @ResponseBody
    public Result<T> checkTemplateManagement() {
        return Result.success();
    }


    //刷新密码
    @PreAuthorize("hasAnyAuthority('ROLE_PLAN','ROLE_PRODUCE','ROLE_QUALITY','QUALITY_INSPECTION','ROLE_CRAFT','ROLE_ADMIN')")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public Result<T> updatePassword(@NotBlank @RequestParam("password") String password) {
        return indexService.doUpdatePassword(password);
    }

    //获取姓名
    @PreAuthorize("hasAnyAuthority('ROLE_PLAN','ROLE_PRODUCE','ROLE_QUALITY','QUALITY_INSPECTION','ROLE_CRAFT','ROLE_ADMIN','ROLE_OTHER')")
    @RequestMapping(value = "/getName", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> getName() {
        return indexService.doGetName();
    }


//
//    @RequestMapping(value = "/none/test", method = RequestMethod.GET)
//    public void test() throws ApiException {
//        String accessToken = dingdingService.getAccessToken();
//        String mobile = "15096008327";
//        if(StringUtils.isBlank(mobile)){
//            return;
//        }
//        StringBuilder userIdList = new StringBuilder();
//        String[] split = mobile.split(",");
//        for(String cell : split){
//            DingTalkClient client2 = new DefaultDingTalkClient(dingdingService.getGetByMobileUrl());
//            OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest();
//            req.setMobile(cell);
//            req.setHttpMethod("GET");
//            OapiUserGetByMobileResponse rsp = client2.execute(req, accessToken);
//            // 获取的urid即为发送的目标人员的ID
//            String urid = rsp.getUserid();
//            // 将接受人员的urid按照（user123,user456）的形式拼接
//            userIdList.append(urid).append(",");
//        }
//        DingTalkClient client = new DefaultDingTalkClient(dingdingService.getAsyncMessageUrl());
//        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
//        request.setUseridList(userIdList.toString());
//        request.setAgentId(dingdingService.getAgentId());
//        request.setToAllUser(false);
//        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
//        // 消息类别时文本消息
//        msg.setMsgtype("text");
//        msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
//        //  msg.getText().setContent("工作通知：你存在未处理的待办任务，请及时处理待办事项！");
//        request.setMsg(msg);
//        // 消息发送
//        OapiMessageCorpconversationAsyncsendV2Response dingResult = client.execute(request, accessToken);
//        System.out.println(gson.toJson(dingResult));
//    }

}
